//
//  PieGraphView.swift
//  SitPosition
//
//  Created by apple on 2019/1/27.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit


struct PieArc {
    let radius: CGFloat
    let startAngle: CGFloat
    let endAngle: CGFloat
    let color: UIColor
}

class PieGraphView : UIView {
    
    // MARK: - Properties
    
    // 线宽 - 圆环的厚度
    public var lineWidth: CGFloat = 20 {
        didSet {
            _rebuildShapeLayers()
        }
    }
    
    // 弧的分段数据
    public var arcs: [PieArc] = [] {
        didSet {
            _rebuildShapeLayers()
        }
    }
    
    // MARK: - Object lifecycle
    
    override func layoutSubviews() {
        super.layoutSubviews()
        _rebuildShapeLayers()
    }
    
    // MARK: - Private Methods
    
    // 重建Layer
    var _layers: [CALayer] = []
    
    private func _rebuildShapeLayers() {
        // 移除先前的子Layer
        for l in _layers {
            l.removeFromSuperlayer()
        }
        _layers.removeAll(keepingCapacity: true)
        
        // 构建新的Layer
        let center: CGPoint = CGPoint(x: bounds.midX, y: bounds.midY)
        for p in arcs {
            let path = UIBezierPath(
                arcCenter: center,
                radius: p.radius,
                startAngle: p.startAngle.radians,
                endAngle: p.endAngle.radians,
                clockwise: true)
            
            let sl: CAShapeLayer = CAShapeLayer()
            sl.path = path.cgPath
            sl.lineWidth = lineWidth
            sl.strokeColor = p.color.cgColor
            sl.fillColor = UIColor.white.cgColor
            layer.addSublayer(sl)
            _layers.append(sl)
        }
    }
}
